/**
 * 分类内容页面逻辑
 */
document.addEventListener('DOMContentLoaded', () => {
    // 全局变量
    const state = {
        currentPage: 1,
        hasMorePages: true,
        isLoading: false,
        categoryId: null,
        categoryName: '',
        wallpapers: []
    };
    
    // DOM元素
    const elements = {
        wallpaperGrid: document.getElementById('wallpaper-grid'),
        categoryTitle: document.getElementById('category-title'),
        backBtn: document.getElementById('back-btn'),
        loadMore: document.getElementById('load-more')
    };
    
    /**
     * 初始化页面
     */
    function init() {
        // 从URL获取分类ID
        const urlParams = new URLSearchParams(window.location.search);
        state.categoryId = urlParams.get('id');
        
        if (!state.categoryId) {
            showError('缺少分类ID参数');
            return;
        }
        
        // 绑定事件
        bindEvents();
        
        // 获取分类信息并加载壁纸
        loadCategoryInfo();
    }
    
    /**
     * 绑定事件处理
     */
    function bindEvents() {
        // 返回按钮点击
        elements.backBtn.addEventListener('click', () => {
            window.location.href = 'categories.html';
        });
        
        // 滚动加载更多
        window.addEventListener('scroll', debounce(() => {
            if (state.isLoading || !state.hasMorePages) return;
            
            const scrollPosition = window.scrollY + window.innerHeight;
            const pageHeight = document.body.scrollHeight - 200; // 提前200px触发
            
            if (scrollPosition > pageHeight) {
                loadMoreWallpapers();
            }
        }, 200));
    }
    
    /**
     * 加载分类信息
     */
    async function loadCategoryInfo() {
        try {
            const response = await API.getCategories();
            const categories = response.data;
            
            // 查找当前分类
            const currentCategory = categories.find(cat => cat.id === state.categoryId);
            
            if (!currentCategory) {
                showError('未找到该分类');
                return;
            }
            
            // 更新状态和UI
            state.categoryName = currentCategory.name;
            elements.categoryTitle.textContent = currentCategory.name;
            
            // 加载该分类的壁纸
            loadCategoryWallpapers();
            
        } catch (error) {
            console.error('加载分类信息失败:', error);
            showError('加载分类信息失败');
        }
    }
    
    /**
     * 加载分类壁纸
     */
    async function loadCategoryWallpapers() {
        if (state.isLoading) return;
        
        state.isLoading = true;
        showLoadingIndicator();
        
        try {
            const response = await API.getWallpapers({
                page: state.currentPage,
                limit: 10,
                category: state.categoryId,
                sort: 'popular'
            });
            
            // 更新分页状态
            updatePaginationState(response.pagination);
            
            // 添加到壁纸列表
            state.wallpapers = [...state.wallpapers, ...response.data];
            
            // 渲染壁纸
            renderWallpapers(response.data);
            
        } catch (error) {
            console.error('加载分类壁纸失败:', error);
            showError('加载分类壁纸失败，请刷新重试');
        } finally {
            state.isLoading = false;
            hideLoadingIndicator();
        }
    }
    
    /**
     * 加载更多壁纸
     */
    function loadMoreWallpapers() {
        if (state.hasMorePages && !state.isLoading) {
            state.currentPage++;
            loadCategoryWallpapers();
        }
    }
    
    /**
     * 更新分页状态
     */
    function updatePaginationState(pagination) {
        state.hasMorePages = pagination.current_page < pagination.total_pages;
        
        // 更新加载更多按钮状态
        if (!state.hasMorePages) {
            elements.loadMore.innerHTML = '<span>已加载全部内容</span>';
        } else {
            elements.loadMore.innerHTML = '<span>上拉加载更多</span>';
        }
    }
    
    /**
     * 渲染壁纸列表
     */
    function renderWallpapers(wallpapers) {
        // 移除加载指示器
        const loadingSpinner = elements.wallpaperGrid.querySelector('.loading-spinner');
        if (loadingSpinner) {
            loadingSpinner.remove();
        }
        
        // 如果没有壁纸，显示空状态
        if (wallpapers.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'empty-state';
            emptyState.innerHTML = `
                <i class="ri-image-line"></i>
                <p>该分类下暂无壁纸</p>
                <a href="categories.html" class="btn">返回分类页</a>
            `;
            elements.wallpaperGrid.appendChild(emptyState);
            return;
        }
        
        // 创建壁纸卡片并添加到网格
        wallpapers.forEach(wallpaper => {
            const wallpaperCard = createWallpaperCard(wallpaper);
            elements.wallpaperGrid.appendChild(wallpaperCard);
        });
        
        // 初始化懒加载
        initLazyLoading();
    }
    
    /**
     * 创建壁纸卡片
     */
    function createWallpaperCard(wallpaper) {
        const isFavorite = Storage.isFavorite(wallpaper.id);
        
        const card = document.createElement('div');
        card.className = 'wallpaper-card';
        card.dataset.id = wallpaper.id;
        
        card.innerHTML = `
            <div class="wallpaper-actions">
                <div class="action-icon favorite ${isFavorite ? 'active' : ''}" data-id="${wallpaper.id}">
                    <i class="ri-heart-${isFavorite ? 'fill' : 'line'}"></i>
                </div>
            </div>
            <img class="wallpaper-img lazy-image" data-src="${wallpaper.thumbnail_url}" alt="${wallpaper.category}壁纸">
            <div class="wallpaper-info">
                <div class="wallpaper-category">${getCategoryName(wallpaper.category)}</div>
            </div>
        `;
        
        // 点击壁纸跳转到详情页
        card.addEventListener('click', (e) => {
            // 避免点击收藏按钮时跳转
            if (!e.target.closest('.action-icon')) {
                Storage.addRecentlyViewed(wallpaper.id);
                window.location.href = `detail.html?id=${wallpaper.id}`;
            }
        });
        
        // 收藏按钮点击
        const favoriteBtn = card.querySelector('.action-icon.favorite');
        favoriteBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止冒泡，避免触发卡片点击
            toggleFavorite(favoriteBtn);
        });
        
        return card;
    }
    
    /**
     * 切换收藏状态
     */
    async function toggleFavorite(buttonElement) {
        const wallpaperId = buttonElement.dataset.id;
        const isFavorite = buttonElement.classList.contains('active');
        
        try {
            if (isFavorite) {
                // 取消收藏
                await API.removeFromFavorites(wallpaperId);
                buttonElement.classList.remove('active');
                buttonElement.innerHTML = '<i class="ri-heart-line"></i>';
            } else {
                // 添加收藏
                await API.addToFavorites(wallpaperId);
                buttonElement.classList.add('active');
                buttonElement.innerHTML = '<i class="ri-heart-fill"></i>';
            }
        } catch (error) {
            console.error('操作收藏失败:', error);
            showToast('操作失败，请重试');
        }
    }
    
    /**
     * 根据分类ID获取分类名称
     */
    function getCategoryName(categoryId) {
        const categoryMap = {
            'nature': '自然风光',
            'city': '城市建筑',
            'abstract': '抽象艺术',
            'minimal': '简约风格',
            'dark': '暗色系',
            'bright': '亮色系'
        };
        
        return categoryMap[categoryId] || categoryId;
    }
    
    /**
     * 显示加载指示器
     */
    function showLoadingIndicator() {
        // 如果不是第一页，显示在底部
        if (state.currentPage > 1) {
            elements.loadMore.innerHTML = `
                <div class="spinner" style="margin: 1rem auto;"></div>
                <span>加载中...</span>
            `;
        }
    }
    
    /**
     * 隐藏加载指示器
     */
    function hideLoadingIndicator() {
        if (state.currentPage > 1) {
            elements.loadMore.innerHTML = '<span>上拉加载更多</span>';
        }
    }
    
    /**
     * 显示错误提示
     */
    function showError(message) {
        elements.wallpaperGrid.innerHTML = `
            <div class="error-message">
                <i class="ri-error-warning-line"></i>
                <p>${message}</p>
                <a href="categories.html" class="btn">返回分类页</a>
            </div>
        `;
    }
    
    /**
     * 显示提示信息
     */
    function showToast(message) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = message;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 触发动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);
        
        // 自动移除
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 2000);
    }
    
    /**
     * 初始化图片懒加载
     */
    function initLazyLoading() {
        const lazyImages = document.querySelectorAll('.lazy-image');
        
        // 使用Intersection Observer实现懒加载
        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        const src = img.dataset.src;
                        
                        // 创建图片对象
                        const tempImg = new Image();
                        tempImg.onload = () => {
                            img.src = src;
                            img.classList.remove('lazy-image');
                        };
                        tempImg.src = src;
                        
                        // 停止观察
                        imageObserver.unobserve(img);
                    }
                });
            }, {
                rootMargin: '50px 0px'
            });
            
            lazyImages.forEach(img => {
                imageObserver.observe(img);
            });
        } else {
            // 回退: 简单地加载所有图片
            lazyImages.forEach(img => {
                img.src = img.dataset.src;
                img.classList.remove('lazy-image');
            });
        }
    }
    
    /**
     * 防抖函数
     */
    function debounce(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(context, args);
            }, wait);
        };
    }
    
    // 初始化
    init();
}); 